// pages/optional/report/major.js
const {
  twoMajorList,
  matchReport,
  schoolReportAdd,
  schoolReportList,
  schoolReportEdit
} = require('../../../api/api')
const selectorRouteDatas = [{
    id: 0,
    title: "全国",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "年份",
    type: "radiobox",
    key: "year",
    items: [
      {
        id: '2024',
        title: '2024'
      },
    ]
  },


]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    filterRouteKey: 'optionalChooseFilters',
    selectedData: {
      province: 0,
      year: '2024'
    },
    selectorDataList: selectorRouteDatas,
    setting: {
      width: '220rpx',
      weight: 'normal',
      color: '#808080',
      fontSize: '26rpx',
      height: '50rpx',
      padding: '0'
    },
    selectedList: [],
    selectedIds: [],
    list: [],
    mode: 'school',
    subjects: [],
    visible: false,
    checkedValue: {},
    myParams: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOptionalTotal()
    const {
      filterRouteKey,
      selectorDataList,
    } = this.data
    var d = new Date()
    var year = d.getFullYear()
    var month=d.getMonth()
    if(month>6){
      year=year+1
    }
    var len=year+1
    var yearList = []
    for (var i = year; i < len; i++) {
      yearList.push({
        id: i,
        title: i
      })
    }
    selectorDataList[1].items = yearList
    this.setData({
      selectorDataList
    })
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      this.setData({
        ...params,
        myParams: params
      })
      const obj = {
        province: params.provinceId,
        year: params.year
      }
      this.setData({
        selectedData: obj,
      })
      wx.setStorageSync(filterRouteKey, obj)
      this.loadData()
    }
    this.fetchCity()
  },
  async getOptionalTotal() {
    const params = {
      pageNo: 1,
      pageSize: 1
    }
    const {
      result
    } = await schoolReportList(params)
    this.setData({
      optionalTotal: result.total,
    })
  },
  async loadData() {
    const {
      selectedIds,
      selectedList,
      mode,
      selectedData
    } = this.data
    const params = {
      year: selectedData.year,
      provinceId: selectedData.province
    }
    if (mode == 'school') {
      params.schoolIds = selectedIds
    } else {
      params.specialNames = selectedList.map((item) => {
        return item.title
      })
    }
    const {
      result
    } = await matchReport(params)
    var subjects = result.bestMatch.split('_')
    this.setData({
      list: result.list,
      subjects
    })
  },
  async fetchCity() {
    const {
      type,
      selectorDataList,
      selectedData
    } = this.data
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    var currentRegions = cityList.filter((item) => {
      return item.id == selectedData.province
    })
    selectorDataList[0].items = cityList
    this.setData({
      selectorDataList,
      currentRegion: currentRegions[0]
    })
    this.filterKeyFunc()
  },
  filterKeyFunc() {
    const selectedData = wx.getStorageSync(this.data.filterRouteKey)
    const {
      selectorDataList,
      cityList
    } = this.data
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
    })
    this.setData({
      selectorDataList,
      selectedData,

    })

  },
  async onSelectChangedRoute(e) {
    wx.setStorageSync(this.data.filterRouteKey, {
      ...e.detail
    });
    const {
      cityList
    } = this.data
    var currentRegions = cityList.filter((item) => {
      return item.id == e.detail.province
    })
    this.filterKeyFunc()
    this.setData({
      ...e.detail,
      currentRegion: currentRegions[0]
    });
  },
  toggelChecked(e) {
    const {
      checked,
      index
    } = e.currentTarget.dataset
    const {
      list
    } = this.data
    list[index].checked = !checked
    this.setData({
      list
    })
  },
  edit() {
    const {
      mode,
      myParams
    } = this.data
    const pages = getCurrentPages()
    const prevpage = pages[pages.length - 2]
    if (mode == 'school') {
      if (prevpage.route == 'pages/optional/school/index') {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.navigateTo({
          url: '/pages/optional/school/index?params=' + encodeURIComponent(JSON.stringify(myParams))
        })
      }
    } else {
      if (prevpage.route == 'pages/optional/major/index') {
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.navigateTo({
          url: '/pages/optional/major/index?params=' + encodeURIComponent(JSON.stringify(myParams))
        })
      }
    }

  },
  openMatch(e) {
    var {
      value
    } = e.currentTarget.dataset
    let subjects = value.subject.split('_')
    let type = subjects[0]
    value['subjects'] = subjects
    value['type'] = type
    this.setData({
      checkedValue: value,
      visible: true,
    })
  },
  goto(e) {
    const {
      url
    } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },

  async confirm() {
    const {
      subjects,
      currentRegion,
      selectedIds,
      selectedList,
      selectedData,
      mode,
      planMatchId
    } = this.data
    const newSelectedList = selectedList.map((item) => {
      return {
        id: item.id,
        title: item.title
      }
    })
    const params = {
      subjects, //科目
      province: currentRegion.title, //城市名称
      provinceId: currentRegion.id, //城市id
      selectedIds, //已选专业/学校id
      selectedList: newSelectedList, //已选专业/学校列表
      year: selectedData.year, //年份
      type: mode,
    }
    if (planMatchId) {
      params.id = planMatchId
      const {
        result
      } = await schoolReportEdit(params)
      wx.showToast({
        title: '修改成功',
        icon: 'none'
      })
    } else {
      const {
        result
      } = await schoolReportAdd(params)
      wx.showToast({
        title: '保存成功',
        icon: 'none'
      })
      this.getOptionalTotal()
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '新高考选科工具',
      imageUrl:'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg',
      path:'/pages/optional/index/index'
    }
  }
})